#include "sendHeartRequest.h"
#include "curlRequestUtil.h"
#include <cjson/cJSON.h>
#include <stdlib.h>
#include "AdDao.h"
#include "AdParseLogic.h"
//解析指令集
void parseCmdList(cJSON* item){
    if (cJSON_IsArray(item))
    {
        int size=cJSON_GetArraySize(item);
        for (int i = 0; i < size; i++)
        {
            cJSON* cmdJson=cJSON_GetArrayItem(item,i);
            if (cJSON_IsNumber(cmdJson))
            {
                int num=cmdJson->valueint;
                switch (num)
                {
                case 1:
                    /* system("shutdown") */
                    printf("关机命令\n");
                    break;
                case 2:
                    // system("reboot")
                    printf("重启命令\n");
                default:
                    break;
                }
            }
        }
    }
}

// 解析cjson转为Ad结构体，并返回
Ad* parseUpDownSplitScr(cJSON* adJson)
{
    Ad * result = (Ad*)calloc(1,sizeof(Ad));
   if (cJSON_IsObject(adJson))
    {
      cJSON *idJson = cJSON_GetObjectItemCaseSensitive(adJson,"id");
      int id = idJson->valueint;
      cJSON *templateIdJson = cJSON_GetObjectItemCaseSensitive(adJson,"template_id");
      int templateId = templateIdJson->valueint;
      cJSON *customerIdJson = cJSON_GetObjectItemCaseSensitive(adJson,"customer_id");
      int customerId = customerIdJson->valueint;
      cJSON *startTimeJson = cJSON_GetObjectItemCaseSensitive(adJson,"start_time");
      char *startTime = startTimeJson->valuestring;
      cJSON *endTimeJson = cJSON_GetObjectItemCaseSensitive(adJson,"end_time");
      char *endTime = endTimeJson->valuestring;
      int state = cJSON_GetObjectItemCaseSensitive(adJson,"state")->valueint;

      result->id  = id;
      result->template_id  = templateId;
      result->customer_id  = customerId;
      result->start_time  = startTime;
      result->end_time  = endTime;
      result->state = state;
      //AdResource *resources[3];

      //广告资源解析
      AdResource *upAr = (AdResource*)calloc(1,sizeof(AdResource));
      upAr->ad_id = id;
      upAr->index = 0;
      cJSON *typeIdJson = cJSON_GetObjectItemCaseSensitive(adJson,"top_media_type_id");
      int typeId = typeIdJson->valueint;
      upAr->type_id = typeId;
      cJSON *urlJson = cJSON_GetObjectItemCaseSensitive(adJson,"top_media_url");
      char *url = urlJson->valuestring;
      upAr->path = url;
      cJSON *signJson = cJSON_GetObjectItemCaseSensitive(adJson,"top_media_sign");
      char *sign = signJson->valuestring;
       upAr->sign = sign;
    
      result->resources[0] =upAr;

       AdResource *buttomAr = (AdResource*)calloc(1,sizeof(AdResource));
      buttomAr->ad_id = id;
      buttomAr->index = 0;
      cJSON *typeIdJson1 = cJSON_GetObjectItemCaseSensitive(adJson,"buttom_media_type_id");
      int typeId1 = typeIdJson1->valueint;
      buttomAr->type_id = typeId1;
      cJSON *urlJson1 = cJSON_GetObjectItemCaseSensitive(adJson,"buttom_media_url");
      char *url1 = urlJson1->valuestring;
      buttomAr->path = url1;
      cJSON *signJson1 = cJSON_GetObjectItemCaseSensitive(adJson,"buttom_media_sign");
      char *sign1 = signJson1->valuestring;
       buttomAr->sign = sign1;
    
      result->resources[1] =buttomAr;
  }
  return result;
}

// 解析播放列表 - 响应回来的广告列表，每一条数据都应该是一个ad结构体对象
void parseAdList(cJSON* adList)
{
    if(cJSON_IsArray(adList))
    {

        int size = cJSON_GetArraySize(adList);
        Ad* ads[size];
        for(int i=0;i<size;i++)
        {
            cJSON* item = cJSON_GetArrayItem(adList,i);
            int templateId = cJSON_GetObjectItemCaseSensitive(item,"template_id")->valueint;
            switch (templateId)
            {
            case 1: // 全屏展示
                break;
            case 2: // 左右分屏
                break;
            case 3: // 左中右分屏
                break;
            case 6: // 上下分屏
                Ad* ad = parseUpDownSplitScr(item);
                ads[i] = ad;
                break;
            default:
                break;
            }
        }

        //  下载并生成本地广告列表保存到sqlite数据库
        int result = downloadAdsAndGenLocalAdListToSqlite(ads,size);

        if(result == 0)
        {
            printf("本次媒体资源没有更新，qt进程不处理\n");
        }else{
            printf("通知qt进程更新播放列表\n");
        }
    }
}

size_t heartWriteCallback(void *contents, size_t size, size_t nmemb, void *userp) {
    size_t realsize = size * nmemb;
    // 这里可以处理获取到的数据，比如存储到文件或者其他操作
    char * result = (char *)contents;

    // 利用cJSONqu解析json字符串
    cJSON* root = cJSON_Parse(result);  // 将json字符串转成json对象
    if(root != NULL)
    {
        cJSON* successJson = cJSON_GetObjectItemCaseSensitive(root,"success");
        cJSON* codeJson = cJSON_GetObjectItemCaseSensitive(root,"code");
        cJSON* messageJson = cJSON_GetObjectItemCaseSensitive(root,"message");

        if(successJson->valueint == 1 && codeJson->valueint == 200)
        {
            //获取data中的数据
            cJSON* dataJson=cJSON_GetObjectItemCaseSensitive(root,"data");
            if (dataJson!=NULL)
            {
                cJSON* adListJson=cJSON_GetObjectItemCaseSensitive(dataJson,"ad_list");
                cJSON* cmdListJson=cJSON_GetObjectItemCaseSensitive(dataJson,"cmd_list");

                //解析cmd_list
                if (cmdListJson!=NULL)
                {
                    parseCmdList(cmdListJson);
                }
                // 解析ad_list
                if(adListJson != NULL)
                {
                    parseAdList(adListJson);
                    printf("广告列表处理完毕\n");
                }
            }
            
        }
        else{
            printf("广告机心跳请求失败!失败:%s\n",messageJson->valuestring);
        }
    }

    //printf("%s\n",result);
    return realsize;
}

void sendHeartRequest(char* gatewayIp,char* sn){
    char* urlFormatStr="http://%s/hearts.json?sn=%s";
    char* url=(char*)calloc(1,100);

    sprintf(url,urlFormatStr,gatewayIp,sn);
    printf("config request url:%s\n",url);
    sendGetRequest(url,heartWriteCallback);
}